<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="24">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>期货账户管理</span>
            </div>
          </template>

          <!-- 搜索区域 -->
          <el-form :inline="true" :model="queryParams" class="search-form">
            <el-form-item label="账户代码" prop="accountCode">
              <el-input v-model="queryParams.accountCode" placeholder="请输入账户代码" clearable />
            </el-form-item>
            <el-form-item label="账户名称" prop="accountName">
              <el-input v-model="queryParams.accountName" placeholder="请输入账户名称" clearable />
            </el-form-item>
            <el-form-item label="期货公司" prop="futuresCompany">
              <el-input v-model="queryParams.futuresCompany" placeholder="请输入期货公司" clearable />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">查询</el-button>
              <el-button icon="RefreshRight" @click="resetQuery">重置</el-button>
              <el-button type="primary" icon="Plus" @click="handleAdd"
                v-hasPermi="['kylin:futureAccount:add']">新增</el-button>
              <el-button type="danger" icon="Delete" :disabled="multiple" @click="handleDelete"
                v-hasPermi="['kylin:futureAccount:delete']">删除</el-button>
              <el-button icon="Download" @click="handleExport"
                v-hasPermi="['kylin:futureAccount:export']">导出</el-button>
            </el-form-item>
          </el-form>

          <!-- 数据表格 -->
          <el-table v-loading="loading" :data="accountList" @selection-change="handleSelectionChange"
            style="width: 100%">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="账户代码" prop="accountCode" align="center" />
            <el-table-column label="账户名称" prop="accountName" align="center" />
            <el-table-column label="期货公司" prop="futuresCompany" align="center" />
            <el-table-column label="期货公司代码" prop="brokerCode" align="center" />
            <el-table-column label="结算单账号" prop="settlementAccount" align="center" />
            <el-table-column label="交易用户名" prop="tradeUsername" align="center" />
            <el-table-column label="交易服务器" prop="tradeServer" align="center" />
            <el-table-column label="行情服务器" prop="marketServer" align="center" />
            <el-table-column label="产品信息" prop="productInfo" align="center" />
            <el-table-column label="操作" align="center" width="150">
              <template #default="scope">
                <el-button type="primary" link icon="Edit" size="small" @click="handleUpdate(scope.row)"
                  v-hasPermi="['kylin:futureAccount:edit']">修改</el-button>
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页 -->
          <pagination v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" :total="total"
            @pagination="getList" />
        </el-card>
      </el-col>
    </el-row>

    <!-- 新增/编辑对话框 -->
    <el-dialog v-model="open" :title="title" width="600px" @close="handleClose">
      <el-form :model="form" :rules="rules" ref="formRef">
        <el-form-item label="账户代码" prop="accountCode">
          <el-input v-model="form.accountCode" placeholder="请输入账户代码" />
        </el-form-item>
        <el-form-item label="账户名称" prop="accountName">
          <el-input v-model="form.accountName" placeholder="请输入账户名称" />
        </el-form-item>
        <el-form-item label="期货公司" prop="futuresCompany">
          <el-input v-model="form.futuresCompany" placeholder="请输入期货公司" />
        </el-form-item>
        <el-form-item label="结算单账号" prop="settlementAccount">
          <el-input v-model="form.settlementAccount" placeholder="请输入结算单账号" />
        </el-form-item>
        <el-form-item label="结算单密码" prop="settlementPassword">
          <el-input v-model="form.settlementPassword" type="password" placeholder="请输入结算单密码" />
        </el-form-item>
        <el-form-item label="交易用户名" prop="tradeUsername">
          <el-input v-model="form.tradeUsername" placeholder="请输入交易用户名" />
        </el-form-item>
        <el-form-item label="交易密码" prop="tradePassword">
          <el-input v-model="form.tradePassword" type="password" placeholder="请输入交易密码" />
        </el-form-item>
        <el-form-item label="期货公司代码" prop="brokerCode">
          <el-input v-model="form.brokerCode" placeholder="请输入期货公司代码" />
        </el-form-item>
        <el-form-item label="交易服务器" prop="tradeServer">
          <el-input v-model="form.tradeServer" placeholder="请输入交易服务器" />
        </el-form-item>
        <el-form-item label="行情服务器" prop="marketServer">
          <el-input v-model="form.marketServer" placeholder="请输入行情服务器" />
        </el-form-item>
        <el-form-item label="产品名称" prop="productName">
          <el-input v-model="form.productName" placeholder="请输入产品名称" />
        </el-form-item>
        <el-form-item label="授权码" prop="authCode">
          <el-input v-model="form.authCode" placeholder="请输入授权码" />
        </el-form-item>
        <el-form-item label="产品信息" prop="productInfo">
          <el-input v-model="form.productInfo" placeholder="请输入产品信息" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleClose">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="FutureAccount">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import Pagination from '@/components/Pagination'
import { listFutureAccount, getFutureAccount, addFutureAccount, updateFutureAccount, delFutureAccount, exportFutureAccount } from '@/api/kylin/futureAccount'

const router = useRouter()

// 表格数据
const accountList = ref([])
const loading = ref(true)
const total = ref(0)

// 分页参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  accountCode: undefined,
  accountName: undefined,
  futuresCompany: undefined
})

// 表单相关
const formRef = ref(null)
const open = ref(false)
const title = ref('')
const form = reactive({
  id: undefined,
  accountCode: '',
  accountName: '',
  futuresCompany: '',
  settlementAccount: '',
  settlementPassword: '',
  tradeUsername: '',
  tradePassword: '',
  brokerCode: '',
  tradeServer: '',
  marketServer: '',
  productName: '',
  authCode: '',
  productInfo: ''
})
const rules = reactive({
  accountCode: [{ required: true, message: '账户代码不能为空', trigger: 'blur' }],
  accountName: [{ required: true, message: '账户名称不能为空', trigger: 'blur' }],
  futuresCompany: [{ required: true, message: '期货公司不能为空', trigger: 'blur' }],
  settlementAccount: [{ required: true, message: '结算单账号不能为空', trigger: 'blur' }],
  settlementPassword: [{ required: true, message: '结算单密码不能为空', trigger: 'blur' }],
  tradeUsername: [{ required: true, message: '交易用户名不能为空', trigger: 'blur' }],
  tradePassword: [{ required: true, message: '交易密码不能为空', trigger: 'blur' }],
  brokerCode: [{ required: true, message: '期货公司代码不能为空', trigger: 'blur' }]
})

// 选中的行
const ids = ref([])
const single = ref(true)
const multiple = ref(true)

// 列表查询
function getList() {
  loading.value = true
  listFutureAccount(queryParams).then(response => {
    if (response.code === 200 && response.data) {
      accountList.value = response.data.rows
      total.value = response.data.total
    }
  }).catch(error => {
    console.error('获取账户列表失败:', error)
    ElMessage.error('获取账户列表失败，请稍后重试')
  }).finally(() => {
    loading.value = false
  })
}

// 搜索
function handleQuery() {
  queryParams.pageNum = 1
  getList()
}

// 重置
function resetQuery() {
  queryParams.accountCode = undefined
  queryParams.accountName = undefined
  queryParams.futuresCompany = undefined
  queryParams.pageNum = 1
  getList()
}

// 多选
function handleSelectionChange(selection) {
  ids.value = selection.map(row => row.id)
  single.value = selection.length <= 1
  multiple.value = !selection.length
}

// 新增
function handleAdd() {
  // 使用resetForm函数统一重置所有表单字段
  resetForm()

  open.value = true
  title.value = '新增账户'
}

// 修改
function handleUpdate(row) {
  resetForm()
  getFutureAccount(row.id).then(response => {
    if (response.code === 200 && response.data) {
      const accountData = response.data
      form.id = accountData.id
      form.accountCode = accountData.accountCode
      form.accountName = accountData.accountName
      form.futuresCompany = accountData.futuresCompany
      form.settlementAccount = accountData.settlementAccount
      form.settlementPassword = accountData.settlementPassword
      form.tradeUsername = accountData.tradeUsername
      form.tradePassword = accountData.tradePassword
      form.brokerCode = accountData.brokerCode
      form.tradeServer = accountData.tradeServer
      form.marketServer = accountData.marketServer
      form.productName = accountData.productName
      form.authCode = accountData.authCode
      form.productInfo = accountData.productInfo
      open.value = true
      title.value = '修改账户'
    }
  }).catch(error => {
    console.error('获取账户详情失败:', error)
    ElMessage.error('获取账户详情失败，请稍后重试')
  })
}

// 删除
function handleDelete() {
  if (ids.value.length === 0) {
    ElMessage.warning('请选择要删除的数据')
    return
  }
  ElMessageBox.confirm('确定要删除选中的账户吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    delFutureAccount({ ids: ids.value }).then(response => {
      if (response.code === 200) {
        ElMessage.success(response.msg || '删除成功')
        getList()
        multiple.value = true
        ids.value = []
      }
    }).catch(error => {
      console.error('删除账户失败:', error)
      const errorMsg = error.response?.data?.msg || '删除账户失败，请稍后重试'
      ElMessage.error(errorMsg)
    })
  })
}

// 导出
function handleExport() {
  exportFutureAccount(queryParams).then((response) => {
    if (response.code === 200 && response.data) {
      const blob = new Blob([response.data], { type: 'application/octet-stream' })
      const link = document.createElement('a')
      const fileName = '期货账户数据_' + new Date().getTime() + '.xlsx'
      link.href = URL.createObjectURL(blob)
      link.download = fileName
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
    }
  }).catch(error => {
    console.error('导出账户数据失败:', error)
    ElMessage.error('导出账户数据失败，请稍后重试')
  })
}

// 提交表单
function submitForm() {
  formRef.value.validate((valid) => {
    if (valid) {
      // 准备提交数据，只包含后端需要的字段
      const submitData = {
        ...form
      }

      if (form.id) {
        updateFutureAccount(submitData).then(response => {
          if (response.code === 200) {
            ElMessage.success(response.msg || '修改成功')
            open.value = false
            getList()
          } else {
            // 显示后端返回的错误信息
            ElMessage.error(response.msg || '修改账户失败')
          }
        }).catch(error => {
          console.error('修改账户失败:', error)
          // 尝试获取后端错误信息
          const errorMsg = error.response?.data?.msg || '修改账户失败，请稍后重试'
          ElMessage.error(errorMsg)
        })
      } else {
        addFutureAccount(submitData).then(response => {
          if (response.code === 200) {
            ElMessage.success(response.msg || '新增成功')
            open.value = false
            getList()
          } else {
            // 显示后端返回的错误信息
            ElMessage.error(response.msg || '新增账户失败')
          }
        }).catch(error => {
          console.error('新增账户失败:', error)
          // 尝试获取后端错误信息
          const errorMsg = error.response?.data?.msg || '新增账户失败，请稍后重试'
          ElMessage.error(errorMsg)
        })
      }
    }
  })
}

// 重置表单
function resetForm() {
  // 重置所有表单字段为空
  form.id = undefined
  form.accountCode = ''
  form.accountName = ''
  form.futuresCompany = ''
  form.settlementAccount = ''
  form.settlementPassword = ''
  form.tradeUsername = ''
  form.tradePassword = ''
  form.brokerCode = ''
  form.tradeServer = ''
  form.marketServer = ''
  form.productName = ''
  form.authCode = ''
  form.productInfo = ''

  // 重置Element Plus表单组件状态
  if (formRef.value) {
    formRef.value.resetFields()
  }
}

// 关闭对话框
function handleClose() {
  open.value = false
  resetForm()
}

// 初始化
onMounted(() => {
  getList()
})
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
}
</style>